﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Dynamic;
using System.Data.SqlClient;
using System.Configuration;
using Model;
using Common;
namespace DAL
{
    public class ConfigDAL
    {

        public static ConfigInfo FindOneByID(int id)
        {
            DataRow dr = CommonDAL.FindOneByID(id, "[config]");
            return Simple_Data(dr);
        }
        public static int Update(ConfigInfo info)
        {
            string sql = string.Format("update [config] set [Token]='{0}',[Ticket]='{1}',[LastEditTime]='{2}' where [ID]={3}", info.Token, info.Ticket, DateTime.Now, info.ID);
            return CommonDAL.ExecuteNoneQuery(sql) ? info.ID : 0;
        }
        public static int Edit(ConfigInfo info)
        {
            string sql = string.Format("update [config] set [MemberMoney]={0},[BackMoney]={1},[ShouXuFei]={2},[ShouXuFei2]={3},[SendCount]={4},[MaxMoney]={5},[MaxRedCount]={6} where [ID]={7}", info.MemberMoney, info.BackMoney, info.ShouXuFei, info.ShouXuFei2, info.SendCount, info.MaxMoney, info.MaxRedCount, info.ID);
            return CommonDAL.ExecuteNoneQuery(sql) ? info.ID : 0;
        }
        public static int UpdateThirdTicket(string ticket)
        {
            string sql = string.Format("update [config] set [ThirdTicket]='{0}' where [ID]=1", ticket);
            return CommonDAL.ExecuteNoneQuery(sql) ? 1 : 0;
        }
        public static int UpdateThirdToken(string token)
        {
            string sql = string.Format("update [config] set [ThirdToken]='{0}',[ThirdLastEditTime]='{1}' where [ID]=1", token, DateTime.Now);
            return CommonDAL.ExecuteNoneQuery(sql) ? 1 : 0;
        }
        private static ConfigInfo Simple_Data(DataRow dr)
        {
            ConfigInfo info = new ConfigInfo();
            if (dr != null)
            {
                info.ID = DataConvert.ToInt(dr["ID"]);
                info.Token = DataConvert.ToString(dr["Token"]);
                info.Ticket = DataConvert.ToString(dr["Ticket"]);
                info.LastEditTime = DataConvert.ToDateTime(dr["LastEditTime"]);
                info.ThirdToken = DataConvert.ToString(dr["ThirdToken"]);
                info.ThirdTicket = DataConvert.ToString(dr["ThirdTicket"]);
                info.ThirdLastEditTime = DataConvert.ToDateTime(dr["ThirdLastEditTime"]);
                info.MemberMoney = DataConvert.ToFloat(dr["MemberMoney"]);
                info.BackMoney = DataConvert.ToFloat(dr["BackMoney"]);
                info.ShouXuFei = DataConvert.ToFloat(dr["ShouXuFei"]);
                info.ShouXuFei2 = DataConvert.ToFloat(dr["ShouXuFei2"]);
                info.SendCount = DataConvert.ToInt(dr["SendCount"]);
                info.MaxMoney = DataConvert.ToFloat(dr["MaxMoney"]);
                info.MaxRedCount = DataConvert.ToFloat(dr["MaxRedCount"]);
            }
            return info;
        }
        public static ConfigInfo GetConfig()
        {
            WeiXin wx = new WeiXin();
            ConfigInfo config = FindOneByID(1);
            if (DateTime.Now > config.LastEditTime.AddHours(1) || !TokenValid(config.Token))
            {
                string token = wx.HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1a4dea3fd54864b9&secret=75fac3337cd918fd762b48f368cba18e", "");
                token = wx.ConvertJson(token).access_token;
                string ticket = GetTickect(token);
                ticket = wx.ConvertJson(ticket).ticket;
                config.Token = token;
                config.Ticket = ticket;
                Update(config);
            }
            return config;
        }
        public static bool TokenValid(string token)
        {
            WeiXin wx = new WeiXin();
            string result = wx.HttpPost("https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + token + "&media_id=1234", "");
            if (result.Contains("access_token"))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public static ConfigInfo GetThirdConfig()
        {
            WeiXin wx = new WeiXin();
            ConfigInfo config = FindOneByID(1);
            if (DateTime.Now > config.ThirdLastEditTime.AddHours(1))
            {
                string token = wx.HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_component_token", string.Format("{{\"component_appid\":\"wxef2c55ebada8928b\",\"component_appsecret\":\"bdc98c6e9bbc0599fe2c4d8491b4511e\",\"component_verify_ticket\":\"{0}\"}}", config.ThirdTicket));
                token = wx.ConvertJson(token).component_access_token;
                config.ThirdToken = token;
                UpdateThirdToken(token);
            }
            return config;
        }
        /// <summary>
        /// 获取预授权码
        /// </summary>
        /// <returns></returns>
        public static string GetPreAthCode()
        {
            WeiXin wx = new WeiXin();
            string token = GetThirdConfig().ThirdToken;
            string json = wx.HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" + token, "{\"component_appid\":\"wxef2c55ebada8928b\"}");
            return wx.ConvertJson(json).pre_auth_code;
        }
        public static dynamic GetAPIAuth(string authcode)
        {
            WeiXin wx = new WeiXin();
            string token = GetThirdConfig().ThirdToken;
            string json = wx.HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + token, string.Format("{{\"component_appid\":\"wxef2c55ebada8928b\",\"authorization_code\":\"{0}\"}}",authcode));
            Commons.Log2(1+json);
            return wx.ConvertJson(json);
        }
        public static dynamic GetAPIAuthInfo(string authorizer_appid)
        {
            WeiXin wx = new WeiXin();
            string token = GetThirdConfig().ThirdToken;
            string json = wx.HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=" + token, string.Format("{{\"component_appid\":\"wxef2c55ebada8928b\",\"authorizer_appid\":\"{0}\"}}", authorizer_appid));
            Commons.Log2(2 + json);
            return wx.ConvertJson(json);
        }


        public static string GetTickect(string access_token)
        {
            WeiXin wx = new WeiXin();
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token);
            return wx.HttpGet(url, "");
        }
    }
}
